package com.voice.call.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.voice.call.entity.RequestTimesLog;
import com.voice.call.mapper.RequestTimesLogMapper;
import com.voice.call.redis.RedisCacheUtil;
import com.voice.call.service.RedisService;
import com.voice.call.utils.DateUtil;

@Service
public class RedisServiceImpl implements RedisService{
	
	
	private final Logger log = LoggerFactory.getLogger(RedisServiceImpl.class);
	
	private static final String lucky_exchange_key="lucky_exchange_%s";
	private static final int lucky_exchange_times=5;//5秒
	
	@Resource
	private RedisCacheUtil redisCacheUtil;
	
	@Resource
	private RequestTimesLogMapper requestTimesLogMapper;
	
	
	private  boolean addRequestLog(Integer uid,String ip) {
		RequestTimesLog entity = new RequestTimesLog();
		entity.setUserId(uid);
		entity.setIp(ip);
		entity.setType("lucky_exchange");
		entity.setCtime(new Date());
		if (requestTimesLogMapper.insert(entity)>0) {
			return true;
		}
		return false;
	}
	
	//超过请求限制
	@Override
	public	boolean isLuckyExchangeOverRequestLimit(Integer uid,String ip) {
		
		String ymd = DateUtil.getNowDateTimeString(DateUtil.DATE_NO_SPACE_FMT);
		String key = String.format(lucky_exchange_key, ymd);
		if (redisCacheUtil.hexists(key, String.valueOf(uid))) {
			
			String recordTime = redisCacheUtil.hget(key, String.valueOf(uid));
			
			Date recorDate = DateUtil.parse(recordTime, DateUtil.DATE_TIME_FMT);
			Date nowDate = new Date();
			long mif=nowDate.getTime() - recorDate.getTime();
		    int second = (int)(mif/1000);
		    log.info("recordTime={},second={}",recordTime,second);
		    if (second<lucky_exchange_times) {
		    	addRequestLog(uid,ip);
				return true;
			}
			
		}
		return false;
	}
	@Override
	public void recordLuckyExchangeTime(Integer uid) {
		String ymd = DateUtil.getNowDateTimeString(DateUtil.DATE_NO_SPACE_FMT);
		String key = String.format(lucky_exchange_key, ymd);
		String timeYMD = DateUtil.getNowDateTimeString(DateUtil.DATE_TIME_FMT);
		redisCacheUtil.hset(key, String.valueOf(uid), timeYMD);
	}
	
	@Override
	public void deleteLuckyExchangeKey(Date deleteDate) {
		try {
			//获取昨天的年月日
			String ymd = DateUtil.getDateTimeString(deleteDate, DateUtil.DATE_NO_SPACE_FMT);
			String key = String.format(lucky_exchange_key, ymd);
			String called_key = String.format(lucky_exchange_key, ymd);
			log.info("批量删除key={}",key);
			log.info("批量删除key={}",called_key);
			redisCacheUtil.batchDel(key);
			redisCacheUtil.batchDel(called_key);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("redis批量删除key异常");
		}
	}

}
